import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { useDiaryStore } from '../store/diaryStore';

interface ChartFilters {
  moods?: string[];
  tags?: string[];
  searchQuery?: string;
  dateRange?: {
    start: Date;
    end: Date;
  };
  template?: string;
}

interface ChartContextType {
  filters: ChartFilters;
  setFilters: (filters: Partial<ChartFilters>) => void;
  clearFilters: () => void;
}

const ChartContext = createContext<ChartContextType | undefined>(undefined);

export const useChartContext = () => {
  const context = useContext(ChartContext);
  if (!context) {
    throw new Error('useChartContext must be used within a ChartProvider');
  }
  return context;
};

interface ChartProviderProps {
  children: ReactNode;
}

export const ChartProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [filtersState, setFiltersState] = useState<ChartFilters>({});
  
  const { setSelectedMood, setSelectedTags, setDateRange, setSelectedTemplate, getTemplateById } = useDiaryStore();
  
  const setFilters = (newFilters: Partial<ChartFilters>) => {
    setFiltersState(prev => ({ ...prev, ...newFilters }));
  };

  const clearFilters = () => {
    setFiltersState({});
    
    // Also clear the store filters
    setSelectedMood('');
    setSelectedTags([]);
    setDateRange(null);
    setSelectedTemplate(null);
  };
  
  // Apply filters to the store whenever filters change
  useEffect(() => {
    if (filtersState.moods && filtersState.moods.length > 0) {
      setSelectedMood(filtersState.moods[0]); // Store supports single mood
    }
    if (filtersState.tags && filtersState.tags.length > 0) {
      setSelectedTags(filtersState.tags);
    }
    if (filtersState.dateRange) {
      setDateRange({
        start: filtersState.dateRange.start.toISOString().split('T')[0],
        end: filtersState.dateRange.end.toISOString().split('T')[0]
      });
    }
    if (filtersState.template) {
      const template = getTemplateById(filtersState.template);
      setSelectedTemplate(template || null);
    }
  }, [filtersState, setSelectedMood, setSelectedTags, setDateRange, setSelectedTemplate, getTemplateById]);

  return (
    <ChartContext.Provider value={{
      filters: filtersState,
      setFilters,
      clearFilters,
    }}>
      {children}
    </ChartContext.Provider>
  );
};